package com.cus.tom.transfer.adapter;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewbinding.ViewBinding;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.cus.tom.transfer.App;
import com.cus.tom.transfer.R;
import com.cus.tom.transfer.bean.FileType;
import com.cus.tom.transfer.bean.MediaData;
import com.cus.tom.transfer.databinding.ItemAlbumBinding;
import com.cus.tom.transfer.databinding.ItemAlbumHeadBinding;
import com.cus.tom.transfer.it.ImgUi;
import com.cus.tom.transfer.utils.Utils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class BatchAdapter extends RecyclerView.Adapter {

    final List list = new LinkedList();
    Set<Long> set = new HashSet<>();
    int count = 0;
    long size = 0;
    ImgUi act;
    protected final int type;

    public BatchAdapter(ImgUi act, int type) {
        this.act = act;
        this.type = type;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == 0) {
            ItemAlbumHeadBinding binding = ItemAlbumHeadBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
            return new HeadHolder(binding);
        } else if (viewType == 1) {
            ItemAlbumBinding binding = ItemAlbumBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
            return new ImgHolder(binding);
        } else if (viewType == 4) {
            ItemAlbumBinding binding = ItemAlbumBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
            return new AudioHolder(binding);
        } else {
            ItemAlbumBinding binding = ItemAlbumBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
            return new AppHolder(binding);
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof HeadHolder) {
            ((HeadHolder) holder).bind(position);
        } else if (holder instanceof ImgHolder) {
            ((ImgHolder) holder).bind(position);
        }
    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }

    @Override
    public int getItemViewType(int position) {
        Object obj = list.get(position);
        if (obj instanceof MediaData) {
            FileType tmp = FileType.valueOf(((MediaData) obj).getType());
            switch (tmp) {
                case APP:
                    return 2;
                case CONTRACT:
                case SMS:
                case CALL:
                    return 3;
                case AUDIO:
                    return 4;
            }
            return 1;
        }
        return 0;
    }

    public void setData(ArrayList list, int page, int num, long size) {
        if (page == 0) {
            this.count = num;
            this.size = size;
            this.list.clear();
            if (list != null) {
                this.list.addAll(list);
            }
            notifyDataSetChanged();
        } else {
            if (list == null || list.isEmpty()) {
                return;
            }
            MediaData data = (MediaData) this.list.get(this.list.size() - 1);
            if (Utils.isSameDate(data.getAddTime(), ((MediaData) list.get(1)).getAddTime())) {
                list.remove(0);
            }
            this.list.addAll(list);
            count += num;
            this.size += size;
            notifyItemRangeInserted(this.list.size(), list.size());
        }
        act.selectChange(count, size);
    }

    class HeadHolder extends RecyclerView.ViewHolder {

        ItemAlbumHeadBinding binding;

        public HeadHolder(ItemAlbumHeadBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }

        void bind(int p) {
            long time = (Long) list.get(p);
            binding.tvTitle.setText(Utils.getDay5(time));
            if (set.contains(time)) {
                binding.tvAllSelect.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.checkbox_on, 0, 0, 0);
            } else {
                binding.tvAllSelect.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.checkbox_off, 0, 0, 0);
            }
            binding.tvAllSelect.setOnClickListener(v -> {
                boolean bo = set.contains(time);
                if (bo) {
                    set.remove(time);
                } else {
                    set.add(time);
                }
                int num = 0, num2 = 1;
                long tmp = 0;
                for (int i = getBindingAdapterPosition() + 1; i < getItemCount(); i++) {
                    Object obj = list.get(i);
                    if (obj instanceof MediaData) {
                        ++num2;
                        if (((MediaData) obj).isSetSelected() == bo) {
                            ++num;
                            tmp += ((MediaData) obj).getSize();
                            ((MediaData) obj).setSetSelected(!bo);
                        }
                    } else {
                        break;
                    }
                }
                if (bo) {
                    size -= tmp;
                    count -= num;
                } else {
                    size += tmp;
                    count += num;
                }
                act.selectChange(count, size);
                notifyItemRangeChanged(getBindingAdapterPosition(), num2);
            });
        }
    }

    final int H = Utils.dp2Px(App.getApp(), 80);

    class AppHolder extends ImgHolder {

        public AppHolder(ItemAlbumBinding binding) {
            super(binding);
            binding.tv.setVisibility(View.VISIBLE);
            binding.ivCover.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            binding.ivCover.getLayoutParams().height = H;
        }

        @Override
        protected void bind(int p) {
            bind(p, binding.ivSelect, itemView);
        }

        @Override
        protected void setImg(MediaData data) {
            if (type == 0) {//收
                if (!apkInfo(data.getPath(), App.getApp(), binding)) {
                    binding.ivCover.setImageResource(R.mipmap.ic_launcher);
                    binding.tv.setText("文件已删除");
                }
            } else {//发
                try {
                    String name = new File(data.getPath()).getName();
                    name = name.substring(0, name.length() - 4);
                    ApplicationInfo info = App.getApp().getPackageManager().getApplicationInfo(name, 0);
                    Drawable d = info.loadIcon(App.getApp().getPackageManager());
                    binding.ivCover.setImageDrawable(d);
                    binding.tv.setText(info.loadLabel(App.getApp().getPackageManager()).toString());
                } catch (Throwable e) {
                    e.printStackTrace();
                    binding.ivCover.setImageResource(R.mipmap.ic_launcher);
                    binding.tv.setText("文件已删除");
                }
            }
        }
    }

    public boolean apkInfo(String absPath, Context context, ItemAlbumBinding binding) {

        PackageManager pm = context.getPackageManager();

        PackageInfo pkgInfo = pm.getPackageArchiveInfo(absPath, PackageManager.GET_ACTIVITIES);

        if (pkgInfo != null) {

            ApplicationInfo appInfo = pkgInfo.applicationInfo;

            /* 必须加这两句，不然下面icon获取是default icon而不是应用包的icon */

            appInfo.sourceDir = absPath;

            appInfo.publicSourceDir = absPath;

            String appName = pm.getApplicationLabel(appInfo).toString();// 得到应用名

            String packageName = appInfo.packageName; // 得到包名

            String version = pkgInfo.versionName; // 得到版本信息

            /* icon1和icon2其实是一样的 */

            Drawable icon1 = pm.getApplicationIcon(appInfo);// 得到图标信息

            Drawable icon2 = appInfo.loadIcon(pm);
            binding.ivCover.setScaleType(ImageView.ScaleType.CENTER);
            binding.ivCover.setImageDrawable(icon2);
            binding.tv.setText(appName);
            return true;
        }
        return false;
    }

    final int H2 = Utils.dp2Px(App.getApp(), 60);

    class AudioHolder extends ImgHolder {
        public AudioHolder(ViewBinding binding2) {
            super(binding2);
            binding.ivCover.getLayoutParams().height = H2;
            binding.ivCover.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            binding.ivCover.setImageResource(R.mipmap.transmit_icon_music_light);
            binding.tv.setVisibility(View.VISIBLE);
        }

        @Override
        protected void setImg(MediaData data) {
            binding.tv.setText(data.getName());
        }
    }

    public class ImgHolder extends RecyclerView.ViewHolder {
        protected ItemAlbumBinding binding;

        public ImgHolder(ViewBinding binding) {
            super(binding.getRoot());
            if (binding instanceof ItemAlbumBinding) {
                this.binding = (ItemAlbumBinding) binding;
            }
        }

        protected void setImg(MediaData data) {
            Glide.with(itemView.getContext())
                    .setDefaultRequestOptions(RequestOptions.centerCropTransform())
                    .load(data.getPath())
//                    .override(data.getWidth(), data.getHeight())
//                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(binding.ivCover);
        }

        protected void bind(int p) {
            bind(p, binding.ivSelect, itemView);
        }

        protected void bind(int p, ImageView ivSelect, View itemView) {
            MediaData data = (MediaData) list.get(p);
            if (data.isSetSelected()) {
                ivSelect.setImageResource(R.mipmap.checkbox_on);
            } else {
                ivSelect.setImageResource(R.mipmap.checkbox_off);
            }
            setImg(data);
            itemView.setOnClickListener(v -> {
                boolean bo = data.isSetSelected();
                data.setSetSelected(!bo);
                if (data.isSetSelected()) {
                    ++count;
                    size += data.getSize();
                    ivSelect.setImageResource(R.mipmap.checkbox_on);
                    int tmp = getBindingAdapterPosition();
                    boolean all = true;
                    int head = -1;
                    for (int i = tmp - 1; i >= 0; i--) {
                        if (list.get(i) instanceof MediaData) {
                            if (!((MediaData) list.get(i)).isSetSelected()) {
                                all = false;
                                break;
                            }
                        } else {
                            head = i;
                            break;
                        }
                    }
                    for (int i = tmp + 1; i < getItemCount(); i++) {
                        if (list.get(i) instanceof MediaData) {
                            if (!((MediaData) list.get(i)).isSetSelected()) {
                                all = false;
                                break;
                            }
                        } else {
                            break;
                        }
                    }
                    if (all && head >= 0) {
                        long time = (Long) list.get(head);
                        if (!set.contains(time) && all) {
                            set.add(time);
                            notifyItemChanged(head);
                        }
                    }
                } else {
                    --count;
                    size -= data.getSize();
                    ivSelect.setImageResource(R.mipmap.checkbox_off);
                    int tmp = getBindingAdapterPosition();
                    for (int i = tmp - 1; i >= 0; i--) {
                        if (list.get(i) instanceof MediaData == false) {
                            long time = (Long) list.get(i);
                            if (set.contains(time)) {
                                set.remove(time);
                                notifyItemChanged(i);
                            }
                            break;
                        }
                    }
                }
                act.selectChange(count, size);
            });
        }
    }

    public ArrayList<MediaData> getSelect() {
        ArrayList tmp = new ArrayList();
        for (Object obj : list) {
            if (obj instanceof MediaData && ((MediaData) obj).isSetSelected()) {
                tmp.add(obj);
            }
        }
        return tmp;
    }

    public Set<Long> getSelectGroup() {
        return set;
    }

    public void selectAll(boolean bo) {
        count = 0;
        size = 0;
        for (Object obj : list) {
            if (obj instanceof MediaData) {
                ((MediaData) obj).setSetSelected(bo);
                if (bo) {
                    ++count;
                    size += ((MediaData) obj).getSize();
                }
            }
        }
        act.selectChange(count, size);
        notifyItemRangeChanged(0, getItemCount());
    }

    public int getSelectCount() {
        return count;
    }

    public long getSelectSize() {
        return size;
    }
}
